package com.dream.learn.myutils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author 凉小枫
 * @detail
 * @date 2022-01-17 15:28
 */
public class FileUtils {
    //全路径
    private static String  UP_FILE_PATH ="D:\\jinbd\\learn\\file\\";

    //相对路径
    private static String  relativeBaseURL ="D:\\jinbd\\learn\\file\\";

    //上传人ID
    private static String  USER_ID ="12345678900";

    public static void main(String[] args) {

//        fileTest();
        //在内存中开辟地址
        Map<String, String> stringStringHashMap = new HashMap<>(24);
        System.out.println("stringStringHashMap.size():"+stringStringHashMap.size());

        //添加数组元素
        stringStringHashMap.put("1","1");
        System.out.println("stringStringHashMap.size(1):"+stringStringHashMap.size());

        int i = tableSizeFor(10);
        System.out.println("III::::"+i);
    }

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= 1 << 30) ? 1 << 30 : n + 1;
    }

    private static void fileTest(){
        File file = new File("E:\\存钱罐\\holidays2021.json");
        String str = readJsonFile(file);
//        boolean empty = str.isEmpty();
        List list = JSONObject.parseObject(str, List.class);
//        map.forEach(map.get("123"));
//        assert list != null;
        List<String> stringList = null ;
        System.out.println(Objects.requireNonNull(list).size());
//        System.out.println(Objects.requireNonNull(stringList).size());

        writeFile(UP_FILE_PATH + "file1.txt");

        String s = base64Img();
        String type = ".jpg";
        Map<String, String> stringStringMap = upFile(s, type);
    }

    /**
     * 读取JSON文件并转化为String
     * http://blog.csdn.net/superit401/article/details/51727739
     * @param jsonFile 文件名
     * @return
     */
    private static String readJsonFile(File jsonFile) {
        String jsonStr = "";
        System.out.println("————开始读取" + jsonFile.getPath() + "文件————");
        FileReader fileReader = null ;
        Reader reader = null ;
        try {
            //File jsonFile = new File(fileName);
            fileReader = new FileReader(jsonFile);//继承了InputStreamReader
            reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuffer sb1 = new StringBuffer();
            sb1.append(1).append("1");
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            jsonStr = sb.toString();
            System.out.println("————读取" + jsonFile.getPath() + "文件结束!————");
            return jsonStr;
        } catch (Exception e) {
            System.out.println("————读取" + jsonFile.getPath() + "文件出现异常，读取失败!————");
            e.printStackTrace();
            return null;
        }finally {
            try {
                if(fileReader != null)
                fileReader.close();

                if(reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void readFile(String fileName){
        File file = new File(fileName);
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(file);
            char[] a = new char[50];
            int read = fileReader.read(a);// 读取数组中的内容
            for (char c : a)
                System.out.print(c); // 一个一个打印字符
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null){
                    fileReader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
    private static void writeFile(String strPath){
        File file = new File(strPath);
        try {
            // 创建不存在的上级目录
            if(!file.getParentFile().exists()){
                boolean mkdirs = file.getParentFile().mkdirs();
            }
            //创建新文件
            boolean newFile = file.createNewFile();
            if(newFile){
                FileWriter writer = new FileWriter(file);
                // 向文件写入内容
                writer.write("This\n is\n an\n example\n");
                writer.flush();
                writer.close();
            }
            System.out.println("————创建新文件" + strPath+ "结束!————");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String,String> upFile(String imgStr, String type){
        Map<String, String> map = new HashMap<>();

        Random random = new Random();
        StringBuilder result = new StringBuilder();

        //创建文件随机名称
        for (int i = 0; i < 18; i++)
            result.append(random.nextInt(10));
        String fileName = result.append(type).toString();

        //文件上传路径 一般在配置文件进行配置，启动时定义，不可轻易改动
        //fileProperties.getUploadPath() + UserUtils.getUserId()
        File destPath = new File( UP_FILE_PATH + USER_ID + "/" + fileName);
        // 创建不存在的目录
        if (!destPath.getParentFile().exists()) {
            boolean mkdirs = destPath.getParentFile().mkdirs();
        }
        //找到图片流，由base64,开始
        String str = imgStr.substring(imgStr.indexOf("base64,") + 7);

        boolean b = generateImage(str, destPath.getPath());
        if (b){
            String filePath = relativeBaseURL + USER_ID + "/" + fileName;
            map.put("fileName", fileName);
            map.put("filePath", filePath);
            return map;
        }else {
            return map;
        }

    }

    private static boolean generateImage(String fileStr, String pathStr){
        if (fileStr == null) {
            return false;
        } else {
            //创建输出流
            FileOutputStream out = null;
            boolean flag;//标志
            try {
                byte[] bytes = Base64.decodeBase64(fileStr);
                for(int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {
                        bytes[i] = (byte)(bytes[i] + 256);
                    }
                }
                out = new FileOutputStream(pathStr);
                out.write(bytes);
                FileWriter writer = new FileWriter(new File(pathStr));
                writer.write(fileStr);

                return true;
            } catch (Exception var14) {
                flag = false;
            } finally {
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException ignored) {
                    }
                }
            }
            return flag;
        }
    }

    private static String base64Img(){

        return "";
    }
}
